import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_study/l10n/app_localizations_delegate.dart';
import 'package:flutter_study/util/firebase_analytics_util.dart';
import 'package:flutter_study/util/log.dart';
import 'package:provider/provider.dart';
import 'package:showcaseview/showcaseview.dart';

import 'firebase_options.dart';
import 'generated/l10n.dart';
import 'provider/model/person.dart';
import 'routes/home_route.dart';
import 'routes/routes.dart';
import 'routes/settings_route.dart';

void main() {
  // 初始化 firebase
  WidgetsFlutterBinding.ensureInitialized();
  Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  ).then((value){
    Log.i("firebase 初始化成功: ${value.name}");
    FirebaseAnalyticsUtil.logEvent(name: "appStart");
  }).catchError((error){
    Log.i("firebase 初始化失败: $error");
  });

  runApp(MyApp());

  //透明沉浸式状态栏
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    statusBarColor: Colors.transparent, // transparent status bar
  ));
}

class MyApp extends StatelessWidget {
  // Flutter在构建页面时，会调用组件的build方法，widget的主要工作是提供一个build()
  // 方法来描述如何构建UI界面（通常是通过组合、拼装其它基础widget）。
  @override
  Widget build(BuildContext context) {
    // MaterialApp 是Material库中提供的Flutter APP框架，通过它可以设置应用的名称、
    // 主题、语言、首页及路由列表等。MaterialApp也是一个widget。
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<Person>(
          create: (context) => Person(),
        ),
      ],
      child: ShowCaseWidget(
        builder: Builder(
          builder: (ctx){
            return MaterialApp(
              debugShowCheckedModeBanner: false,
              //应用名称
              title: 'Flutter Demo',
              // 路由首页
              theme: ThemeData(
                //蓝色主题
                primarySwatch: Colors.blue,
              ),
              // 注册路由表（命名路由）
              routes: Routes.routes,
              localizationsDelegates: [
                GlobalCupertinoLocalizations.delegate,
                GlobalMaterialLocalizations.delegate,
                AppLocalizationsDelegate(),
                S.delegate,
              ],
              supportedLocales: [
                const Locale("en", "US"),
                const Locale("zh", "CN"),
              ],
              localeListResolutionCallback: (locales, supportedLocales) {
                Log.i("locale change, locales: $locales, supportedLocales: $supportedLocales");
              },
            );
          },
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<StatefulWidget> {
  int _selectedIndex = 0;
  GlobalKey _one = GlobalKey();
  GlobalKey _two = GlobalKey();

  List<Widget> _widgetOptions = <Widget>[
    HomeRoute(),
    SettingsRoute()
  ];

  PageController _pageController = new PageController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ShowCaseWidget.of(context).startShowCase([_one]);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView.builder(
        itemBuilder: (context,index) => _widgetOptions[index],
        itemCount: _widgetOptions.length,
        physics: NeverScrollableScrollPhysics(),
        onPageChanged: (index){
          onPage(index);
        } ,
        controller: _pageController,
      ),
      bottomNavigationBar: Showcase(
        key: _one,
        title: "Menu title",
        description: "Click here to see menu options",
        disposeOnTap: false,
        showArrow: false,
        tooltipPosition: TooltipPosition.top,
        onTargetClick: (){
          Log.i("onTargetClick");
        },
        onToolTipClick: (){
          Log.i("onToolTipClick");
        },
        onBarrierClick: (){
          Log.i("onBarrierClick");
        },
        child: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
            BottomNavigationBarItem(icon: Icon(Icons.settings), label: "Settings"),
          ],
          currentIndex: _selectedIndex,
          fixedColor: Colors.blue,
          onTap: (index){
            _pageController.jumpToPage(index);
          },
        ),
      ),
    );
  }

  void onPage(int index) {
    setState(() {
      if(_selectedIndex != index){
        _selectedIndex = index;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }
}